package com.amiba.crm.admin.auth.core.validate.code;

import com.amiba.crm.admin.common.constant.CommonConstants;
import com.google.code.kaptcha.Producer;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 *
 * 验证码生成逻辑处理类
 */
@Slf4j
@RestController
@AllArgsConstructor
public class ImageCodeHandler{
	private final Producer producer;
	private final RedisTemplate redisTemplate;

	@RequestMapping("/code")
	@SneakyThrows
	public void handle(String randomStr, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成验证码
		String text = producer.createText();
		BufferedImage image = producer.createImage(text);

		//保存验证码信息
		redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CODE_KEY + randomStr, text, 60, TimeUnit.SECONDS);

		// 转换流信息写出
		ServletOutputStream out = response.getOutputStream();
		try {
			ImageIO.write(image, "jpeg", out);
		} catch (IOException e) {
			log.error("ImageIO write err", e);

		}
	}
}
